package com.file;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;


public class MergeMultipleFile {

	public static void main(String args[]){
		File file1 = new File("C:\\speed\\workspace\\test\\src\\com\\file\\file1.txt");
		File file2 = new File("C:\\speed\\workspace\\test\\src\\com\\file\\file2.txt");

		// File to write
		File file3 = new File("C:\\speed\\workspace\\test\\src\\com\\file\\file3.txt");

		File[] files = new File[2];
		files[0] = file1;
		files[1] = file2;
 
 
		mergeFiles(files, file3);
	}
	public static void mergeFiles(File[] files, File mergedFile) {
		 
		FileWriter fstream = null;
		BufferedWriter out = null;
		try {
			fstream = new FileWriter(mergedFile, true);
			 out = new BufferedWriter(fstream);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
 
		for (File f : files) {
			System.out.println("merging: " + f.getName());
			FileInputStream fis;
			try {
				fis = new FileInputStream(f);
				BufferedReader in = new BufferedReader(new InputStreamReader(fis));
 
				String aLine;
				while ((aLine = in.readLine()) != null) {
					out.write(aLine);
					out.newLine();
				}
 
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
 
		try {
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
 
	}
}
